package cn.edu.ncu.housinghub.mapper;

import cn.edu.ncu.housinghub.entity.checkout.Checkout;
import cn.edu.ncu.housinghub.entity.checkout.CheckoutResult;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 退租申请数据访问层
 */
@Mapper
public interface CheckoutMapper {
    
    /**
     * 插入退租申请
     */
    @Insert("INSERT INTO checkout (tenantId, contractId, applyDate, checkoutReason, checkoutStatus, isDeleted) " +
            "VALUES (#{userId}, #{contractId}, #{applyDate}, #{checkoutReason}, #{checkoutStatus}, #{isDeleted})")
    @Options(useGeneratedKeys = true, keyProperty = "checkoutId")
    int insertCheckout(Checkout checkout);
    
    /**
     * 插入退租结果
     */
    @Insert("INSERT INTO checkout_result (checkoutId, checkoutDate, penaltyAmount, depositDeductionAmount) " +
            "VALUES (#{checkout.checkoutId}, #{checkoutDate}, #{penaltyAmount}, #{depositDeductionAmount})")
    @Options(useGeneratedKeys = true, keyProperty = "checkoutResultId")
    int insertCheckoutResult(CheckoutResult checkoutResult);
    
    /**
     * 根据租客ID查询退租申请列表
     */
    @Select("SELECT c.checkoutId, c.tenantId, c.contractId, c.applyDate, c.checkoutReason, c.checkoutStatus, " +
            "ct.startDate, ct.endDate, ct.monthRent, h.houseSummary, h.houseLocation " +
            "FROM checkout c " +
            "LEFT JOIN contract ct ON c.contractId = ct.contractId " +
            "LEFT JOIN house h ON ct.houseId = h.houseId " +
            "WHERE c.tenantId = #{tenantId} AND (c.isDeleted = 0 OR c.isDeleted IS NULL) " +
            "ORDER BY c.applyDate DESC")
    @Results({
        @Result(property = "checkoutId", column = "checkoutId"),
        @Result(property = "userId", column = "tenantId"),
        @Result(property = "contractId", column = "contractId"),
        @Result(property = "applyDate", column = "applyDate"),
        @Result(property = "checkoutReason", column = "checkoutReason"),
        @Result(property = "checkoutStatus", column = "checkoutStatus")
    })
    List<Checkout> selectByTenantId(Long tenantId);
    
    /**
     * 根据房东ID查询退租申请列表
     */
    @Select("SELECT c.checkoutId, c.tenantId, c.contractId, c.applyDate, c.checkoutReason, c.checkoutStatus, " +
            "ct.startDate, ct.endDate, ct.monthRent, h.houseSummary, h.houseLocation, u.username " +
            "FROM checkout c " +
            "LEFT JOIN contract ct ON c.contractId = ct.contractId " +
            "LEFT JOIN house h ON ct.houseId = h.houseId " +
            "LEFT JOIN user u ON c.tenantId = u.userId " +
            "WHERE h.landLordId = #{landlordId} AND (c.isDeleted = 0 OR c.isDeleted IS NULL) " +
            "ORDER BY c.applyDate DESC")
    @Results({
        @Result(property = "checkoutId", column = "checkoutId"),
        @Result(property = "userId", column = "tenantId"),
        @Result(property = "contractId", column = "contractId"),
        @Result(property = "applyDate", column = "applyDate"),
        @Result(property = "checkoutReason", column = "checkoutReason"),
        @Result(property = "checkoutStatus", column = "checkoutStatus")
    })
    List<Checkout> selectByLandlordId(Long landlordId);
    
    /**
     * 根据ID查询退租申请详情
     */
    @Select("SELECT c.checkoutId, c.tenantId, c.contractId, c.applyDate, c.checkoutReason, c.checkoutStatus, " +
            "ct.startDate, ct.endDate, ct.monthRent, h.houseSummary, h.houseLocation, u.username " +
            "FROM checkout c " +
            "LEFT JOIN contract ct ON c.contractId = ct.contractId " +
            "LEFT JOIN house h ON ct.houseId = h.houseId " +
            "LEFT JOIN user u ON c.tenantId = u.userId " +
            "WHERE c.checkoutId = #{checkoutId}")
    @Results({
        @Result(property = "checkoutId", column = "checkoutId"),
        @Result(property = "userId", column = "tenantId"),
        @Result(property = "contractId", column = "contractId"),
        @Result(property = "applyDate", column = "applyDate"),
        @Result(property = "checkoutReason", column = "checkoutReason"),
        @Result(property = "checkoutStatus", column = "checkoutStatus")
    })
    Checkout selectById(Long checkoutId);
    
    /**
     * 更新退租申请状态
     */
    @Update("UPDATE checkout SET checkoutStatus = #{status} WHERE checkoutId = #{checkoutId}")
    int updateCheckoutStatus(@Param("checkoutId") Long checkoutId, @Param("status") Integer status);
    
    /**
     * 检查租客是否有权限对该合同申请退租
     */
    @Select("SELECT COUNT(*) > 0 FROM contract c " +
            "WHERE c.tenantId = #{tenantId} AND c.contractId = #{contractId} " +
            "AND c.signStatus = 5")
    boolean checkTenantPermission(@Param("tenantId") Long tenantId, @Param("contractId") Long contractId);
    
    /**
     * 检查是否已经有未处理的退租申请
     */
    @Select("SELECT COUNT(*) > 0 FROM checkout c " +
            "WHERE c.tenantId = #{tenantId} AND c.contractId = #{contractId} " +
            "AND c.checkoutStatus = 0 AND (c.isDeleted = 0 OR c.isDeleted IS NULL)")
    boolean checkExistingApplication(@Param("tenantId") Long tenantId, @Param("contractId") Long contractId);
    
    /**
     * 检查房东是否有权限处理该退租申请
     */
    @Select("SELECT COUNT(*) > 0 FROM checkout c " +
            "LEFT JOIN contract ct ON c.contractId = ct.contractId " +
            "LEFT JOIN house h ON ct.houseId = h.houseId " +
            "WHERE c.checkoutId = #{checkoutId} AND h.landLordId = #{landlordId}")
    boolean checkLandlordPermission(@Param("landlordId") Long landlordId, @Param("checkoutId") Long checkoutId);
    
    /**
     * 根据租客ID查询退租结果列表
     */
    @Select("SELECT cr.checkoutResultId, cr.checkoutId, cr.checkoutDate, cr.penaltyAmount, cr.depositDeductionAmount, " +
            "c.applyDate, c.checkoutReason, h.houseSummary, h.houseLocation " +
            "FROM checkout_result cr " +
            "LEFT JOIN checkout c ON cr.checkoutId = c.checkoutId " +
            "LEFT JOIN contract ct ON c.contractId = ct.contractId " +
            "LEFT JOIN house h ON ct.houseId = h.houseId " +
            "WHERE c.tenantId = #{tenantId} " +
            "ORDER BY cr.checkoutDate DESC")
    @Results({
        @Result(property = "checkoutResultId", column = "checkoutResultId"),
        @Result(property = "checkout.checkoutId", column = "checkoutId"),
        @Result(property = "checkoutDate", column = "checkoutDate"),
        @Result(property = "penaltyAmount", column = "penaltyAmount"),
        @Result(property = "depositDeductionAmount", column = "depositDeductionAmount")
    })
    List<CheckoutResult> selectCheckoutResultsByTenantId(Long tenantId);
}
